/**
 *
 */
package com.longrise.android.byjk.utils;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.common.DownloadConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.upload_offline.DBHelper;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.PrintLog;
import com.longrise.filedownloader.DownloadManager;
import com.longrise.filedownloader.DownloadService;

import java.io.File;

/**
 * simple introduction
 * <p/>
 * <p/>
 * detailed comment
 *
 * @author Administrator 2015-12-31
 * @see
 * @since 1.0
 */
public class FileUtil {

    private static final String TAG = "FileUtil";

    /**
     * 创建文件夹
     *
     * @param folderName
     */
    public static void createFolder(String folderName) {
        File dir = new File(folderName);
        if (!dir.exists()) {
            if (!dir.isDirectory()) {
                dir.mkdirs();
            }
        }
    }

    /**
     * 删除文件夹
     *
     * @param folderName
     */
    public static void deleteFolder(String folderName) {
        File dir = new File(folderName);
        if (dir.exists()) {
            clearFolder(dir);
            dir.delete();
        }
    }

    /**
     * 判断文件本地时候存在
     *
     * @param fileName
     * @return
     */
    public static boolean isFileExists(String fileName) {
        File file = new File(fileName);
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除文件夹内的数据
     *
     * @param dir
     */
    public static void clearFolder(File dir) {
        if (dir.exists()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    clearFolder(file);
                }
                file.delete();
            }
        }
    }

    /**
     * 得到指定文件夹大小
     */
    public static long getFolderSize(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        if (flist == null) {
            return 0;
        }
        int length = flist.length;
        for (int i = 0; i < length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFolderSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }

    public static String getFileSize(String path) {
        File file = new File(path);
        if (file != null) {
            long length = file.length();
            return FormetFileSize(length);
        } else {
            return 0 + "";
        }
    }

    /**
     * 大小转换 B KB M G
     */
    public static String FormetFileSize(long fileS) {// 转换文件大小
//		DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = String.format("%.2f", (double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = String.format("%.2f", (double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = String.format("%.2f", (double) fileS / 1048576) + "M";
        } else {
            fileSizeString = String.format("%.2f", (double) fileS / 1073741824) + "G";
        }
        if (fileSizeString.equals("0.00B")) {
            return "0B";
        }
        return fileSizeString;
    }

    public static long getSystemAvailableSDCradSize() {
        long blockSize;
        long totalBlocks;
        long availableBlocks;
        File path = Environment.getExternalStorageDirectory();
        StatFs s = new StatFs(path.getPath());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            blockSize = s.getBlockSizeLong();  //占用字节数
//			totalBlocks = s.getBlockCountLong();
            availableBlocks = s.getAvailableBlocksLong();
        } else {
            blockSize = s.getBlockSize();
//					totalBlocks = s.getBlockCount();
            availableBlocks = s.getAvailableBlocks(); //有效block
        }
        return blockSize * availableBlocks;
    }

    /**
     * 判断视频本地是否有下载完成
     */
    public static boolean isHasDownloaded(Context context, String userId, String cwId) {
        DBHelper dbHelper = new DBHelper(context);
        boolean result = false;
        SQLiteDatabase db = null;
        Cursor cursor = null;
        long length = 0;
        long totalLength = 0;
        try {
            db = dbHelper.getWritableDatabase();
            cursor = db.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL +
                    " where userID = ? and cwID = ? ", new String[]{userId, cwId});
            if (cursor.moveToNext()) {
                //Float totalLength = cursor.getFloat(cursor.getColumnIndex("totalLength"));
                String downloadurl = cursor.getString(cursor.getColumnIndex("downloadurl"));
                String cachepath = cursor.getString(cursor.getColumnIndex("cachepath"));
                PrintLog.d(TAG, "downloadurl:" + downloadurl);
                DownloadManager downloadManager = DownloadService.getDownloadManager();
                totalLength = downloadManager.getFileSize(downloadurl);

//                最开始是用的Loadmanager做的下载 后来统一使用downloadmanager
//                if(totalLength==0){
//                    boolean hasThisTask = downloadManager.isHasThisTask(downloadurl);
//                    if(!hasThisTask){ //兼容低版本
//                        LoadDataManager.getInstance().setUserflag(UserInfor.getInstance().getUserid());
//                        EntityBean bean = LoadDataManager.getInstance(context).getDownInfoForDownPath(downloadurl);
//                        if (bean != null) {
//                            String totalFile = bean.getString("totalLength");
//                            if (totalFile != null) {
//                                totalLength = Long.parseLong(totalFile);
//                            }
//                        }
//                    }
//                }

                File file = new File(cachepath);
                if (file.exists()) {
                    length = file.length();
                    PrintLog.d(TAG, "totalLength:" + totalLength);
                    PrintLog.d(TAG, "length:" + length);
                    if (length == totalLength && totalLength != 0) {
                        result = true;
                    }
                }

            }

        } catch (Exception e) {
            PrintLog.d(TAG, "exception:" + e.toString());
            e.printStackTrace();
        }finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return result;
    }


}
